package com.itgacl.magic4j.modules.alipay.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.itgacl.magic4j.libcommon.exception.Magic4jException;
import com.itgacl.magic4j.modules.alipay.config.AlipayConfig;
import com.itgacl.magic4j.modules.alipay.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;

/**
 * @author 徐达沛
 * @version 1.0
 * @description: 支付宝开放平台服务
 * @date 2021/9/9 13:31
 */
@Slf4j
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public AlipaySystemOauthTokenResponse getOauthToken(String code) {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getAlipayGatewayUrl(),alipayConfig.getAppId(),alipayConfig.getAppPrivateKey(),alipayConfig.getFormat(),alipayConfig.getCharset(),alipayConfig.getAlipayPublicKey(),alipayConfig.getSignType());
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");//表示换取使用用户授权码code换取授权令牌access_token
        request.setCode(code);//授权码，用户对应用授权后得到
        try {
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                return response;
            } else {
              return null;
            }
        }catch (Exception e){
            log.error("获取AlipaySystemOauthToken出错："+e.getMessage(),e);
        }
        return null;
    }

    /**
     * 获取支付宝会员授权信息
     * @param accessToken 访问token
     * @return AlipayUserInfoShareResponse
     */
    @Override
    public AlipayUserInfoShareResponse getAlipayUserInfo(String accessToken) {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getAlipayGatewayUrl(),alipayConfig.getAppId(),alipayConfig.getAppPrivateKey(),alipayConfig.getFormat(),alipayConfig.getCharset(),alipayConfig.getAlipayPublicKey(),alipayConfig.getSignType());
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        try {
            AlipayUserInfoShareResponse response = alipayClient.execute(request,accessToken);
            if(response.isSuccess()){
                return response;
            } else {
                return null;
            }
        }catch (Exception e){
            log.error("获取AlipayUserInfo出错："+e.getMessage(),e);
        }
        return null;
    }

    /**
     * 构建授权登录URL
     * @param redirectUri
     * @param scope
     * @param state
     * @return
     */
    @Override
    public String buildAuthorizationUrl(String redirectUri, String scope, String state) {
        try {
            String encodeUri = URLEncoder.encode(redirectUri, "utf-8");//对URL进行编码
            return alipayConfig.getOpenAuthUrl()+"?app_id="+alipayConfig.getAppId()+"&scope="+scope+"&redirect_uri="+encodeUri+"?state="+state;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            throw new Magic4jException("构建授权登录地址异常，错误信息："+e.getMessage());
        }

    }
}
